package com.heima.admin.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminChannelMapper;
import com.heima.admin.service.AdminChannelService;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminChannelServiceImpl extends ServiceImpl<AdminChannelMapper, WmChannel> implements AdminChannelService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private IWemediaClient iWemediaClient;

    /**
     * 查询全部频道
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {
        List<String> channelList = cacheService.lRange("wm_channel_list", 0, -1);
        if (channelList == null) {
            List<WmChannel> wmChannels = new ArrayList<>();
            for (String channel : channelList) {
                WmChannel wmChannel = JSON.parseObject(channel, WmChannel.class);
                wmChannels.add(wmChannel);
            }
            return ResponseResult.okResult(wmChannels);
        } else {
            //redis中没有，先查询数据库，将数据库中的数据同步到redis中，远程调用查询数据库
            List<WmChannel> list = iWemediaClient.selectChannel();
            for (WmChannel channel : list) {
                cacheService.lLeftPush("wm_channel_list", JSON.toJSONString(channel));
            }
            return ResponseResult.okResult(list);
        }
    }
}